package com.wushijia.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class NettyClient {
//  private final String

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringEncoder()).addFirst(new FirstClientHandler());
                    }
                });
        Channel channel = bootstrap.connect("127.0.0.1", 9000).channel();
//        while (true) {
//            channel.writeAndFlush("hello world");
//            Thread.sleep(2000);
//        }
//    channel.writeAndFlush(new BaseMessage(001, "hello world", new Date()));
    }

    private static class FirstClientHandler extends ChannelInboundHandlerAdapter {
        // 客户端连接建立成功之后被调用
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(new Date() + " 客户端写出数据");
            ByteBuf buf = getByteBuf(ctx);
            ctx.channel().writeAndFlush(buf);
        }

        // 客户端连接建立成功之后被调用
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            System.out.println(new Date() + " 客户端读到数据" + buf.toString(StandardCharsets.UTF_8));
        }

        private ByteBuf getByteBuf(ChannelHandlerContext channelHandlerContext) {
            ByteBuf buf = channelHandlerContext.alloc().buffer();
            byte[] bytes = "你好".getBytes(StandardCharsets.UTF_8);
            buf.writeBytes(bytes);
            return buf;
        }
    }
}
